import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Modal } from 'antd';
import {
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaLocaleProvider,
  WeaPopoverHrm,
} from 'ecCom';
import { WeaTableNew, WeaForm } from 'comsMobx';

let WeaTable = WeaTableNew.WeaTable;
import CoworkConstant from '../util/CoworkConstant';
import * as CoworkUtil from '../util/CoworkUtil';

const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel;
const { viewer } = WeaTools;
/**
 * 协作申请
 */
@inject('coworkApplyStore')
@observer
class Apply extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.props.coworkApplyStore.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.props.coworkApplyStore.doInit();
    }
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { coworkApplyStore } = this.props;

    coworkApplyStore.setShowSearchAd(false);
    let selectedKey = 'apply';
    coworkApplyStore.setSelectedKey(selectedKey);
    coworkApplyStore.clearFormFields();
    coworkApplyStore.form = new WeaForm(); // fix 切换报错问题
  }

  render() {
    const { coworkApplyStore } = this.props;
    const {
      comsWeaTableStore,
      loading,
      form,
      topTab,
      selectedKey,
      showSearchAd,
      topTabCounts,
      sessionkey,
    } = coworkApplyStore;

    let conditioninfo = this.getApplyPageCondition();
    const tabBtnsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@3dgnms@search`}
        type="primary"
        onClick={this.ontabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@fq46kf@reset`}
        type="ghost"
        onClick={this.ontabReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@5s0r12@cancel`}
        type="ghost"
        onClick={this.ontabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];

    return (
      <div className="wea-cowork-Apply">
        <WeaPopoverHrm
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaPopoverHrm@rt8ty1`}
        />
        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@8hsoq6`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@yyj2qa`}
            title={getLabel(33842, '协作申请')}
            loading={loading}
            icon={CoworkConstant.icon}
            iconBgcolor={CoworkConstant.iconBgColor}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
            buttons={this.getTopButtons()}
          >
            <WeaTab
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTab@5hi8ty`}
              datas={topTab}
              keyParam="groupid"
              countParam="groupid"
              counts={topTabCounts}
              onChange={this.changeTab}
              selectedKey={selectedKey}
              searchType={['base', 'advanced']}
              searchsBaseValue={
                form.isFormInit &&
                form.getFormParams() &&
                form.getFormParams().name
              }
              setShowSearchAd={this.setShowSearchAd}
              showSearchAd={showSearchAd}
              hideSearchAd={this.hideSearchAd}
              searchsAd={CoworkUtil.getSearchs(form, conditioninfo, () => {
                coworkApplyStore.setShowSearchAd(false);
                coworkApplyStore.doTableLoading();
              })}
              buttonsAd={tabBtnsAd}
              onSearch={this.onSearch}
              onSearchChange={this.onSearchChange}
            />
            <WeaTable
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTable@2xs0s9`}
              comsWeaTableStore={comsWeaTableStore}
              loading={loading}
              sessionkey={sessionkey}
              needScroll={true}
              hasOrder={true}
              getColumns={this.getNewColumns}
              onOperatesClick={this.onOperatesClick}
            />
          </WeaTop>
        </WeaRightMenu>
      </div>
    );
  }

  setShowSearchAd = (bool) => {
    this.props.coworkApplyStore.setShowSearchAd(bool);
  };
  hideSearchAd = () => this.props.coworkApplyStore.setShowSearchAd(false);
  onSearch = () => {
    this.props.coworkApplyStore.doTableLoading();
  };
  onSearchChange = (v) => {
    this.props.coworkApplyStore.appendFormFields({ name: v });
  };

  // 切换tab事件
  changeTab = (theKey) => {
    const { coworkApplyStore } = this.props;
    coworkApplyStore.setSelectedKey(theKey);
    let conditioninfo = this.getApplyPageCondition();
    coworkApplyStore.reinitializeForm(conditioninfo);

    this.executeSearch();
  };

  // top中的按钮
  getTopButtons() {
    const { coworkApplyStore } = this.props;
    const { selectedKey } = coworkApplyStore;
    let _disabled = !this.getTableSelectedValues().length;
    const buttons = [];
    switch (selectedKey) {
      case 'apply':
        buttons.push(
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@5hvl75@apply`}
            type="primary"
            disabled={_disabled}
            onClick={this.batchApply}
          >
            {getLabel(83219, '批量申请')}
          </Button>,
        );
        break;
      case 'approval':
        buttons.push(
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@b1qjiz@approval`}
            type="primary"
            disabled={_disabled}
            onClick={this.batchApproval}
          >
            {getLabel(83212, '批量批准')}
          </Button>,
        );
        buttons.push(
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@hh18je@refuse`}
            type="primary"
            disabled={_disabled}
            onClick={this.batchARefuse}
          >
            {getLabel(83213, '批量拒绝')}
          </Button>,
        );
        break;
      case 'applyLog':
        break;
    }
    return buttons;
  }

  // 右键菜单
  getRightMenu() {
    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });
    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    // btns.push({ key: "collection", icon: <i className='icon-coms-Custom'/>, content: '收藏' });
    // btns.push({ key: "help", icon: <i className='icon-coms-Custom'/>, content: '帮助' });
    return btns;
  }
  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { coworkApplyStore } = this.props;
    if (key == 'search') {
      this.executeSearch();
    } else if (key == 'ShowCustomColumns') {
      const { comsWeaTableStore, sessionkey } = toJS(coworkApplyStore);
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    }
  };

  // 执行搜索方法（也可用于刷新table）
  executeSearch = () => {
    const { coworkApplyStore } = this.props;
    coworkApplyStore.setShowSearchAd(false);
    coworkApplyStore.doTableLoading();
  };

  batchApply = () => {
    this.executeButtonMethod('batchApply');
  };
  batchApproval = () => {
    this.executeButtonMethod('batchApproval');
  };
  batchARefuse = () => {
    this.executeButtonMethod('batchARefuse');
  };
  executeButtonMethod(type, values) {
    const { coworkApplyStore } = this.props;
    if (!values) {
      values = this.getTableSelectedValues();
    }
    let reloadTable = this.executeSearch;
    let updatenum = this.updatenum;

    switch (type) {
      case 'batchApply': {
        confirm({
          title: getLabel(83217, '确认申请加入吗？'),
          content: '',
          onOk() {
            coworkApplyStore.coworkApplayInfo(
              {
                coworkIds: values,
              },
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
      case 'batchApproval': {
        confirm({
          title: getLabel(4914, '确定批准？', 'note'),
          content: '',
          onOk() {
            coworkApplyStore.coworkApplayApproveInfo(
              {
                applyIds: values,
                status: 1,
              },
              updatenum,
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
      case 'batchARefuse': {
        confirm({
          title: getLabel(4915, '确定拒绝？', 'note'),
          content: '',
          onOk() {
            coworkApplyStore.coworkApplayApproveInfo(
              {
                applyIds: values,
                status: 0,
              },
              updatenum,
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
    }
  }

  updatenum = () => {
    WeaTools.callApi('/workflow/request/menuCount.jsp', 'POST', {
      levelid: '638',
    }).then((result) => {
      let num_638 = result.num_638;
      if (document.getElementById('num_638')) {
        document.getElementById('num_638').innerHTML = num_638;
      }
    });
  };

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues() {
    const { coworkApplyStore } = this.props;
    const { comsWeaTableStore } = coworkApplyStore;
    let values = comsWeaTableStore.selectedRowKeysAllPages;
    return values;
  }

  getApplyPageCondition() {
    const { coworkApplyStore } = this.props;
    const { selectedKey, conditioninfo } = toJS(coworkApplyStore);
    if (conditioninfo && conditioninfo.length > 0) {
      let index = 0;
      switch (selectedKey) {
        case 'apply':
          index = 0;
          break;
        case 'approval':
          index = 1;
          break;
        case 'applyLog':
          index = 2;
          break;
        case 'applyquited':
          index = 3;
          break;
        default:
          index = 0;
          break;
      }
      return conditioninfo[index];
    }
    return [];
  }

  ontabSearch = () => {
    const { coworkApplyStore } = this.props;
    coworkApplyStore.setShowSearchAd(false);
    coworkApplyStore.doTableLoading();
  };
  ontabReset = () => {
    const { coworkApplyStore } = this.props;
    coworkApplyStore.clearFormFields();
  };
  ontabCancel = () => {
    const { coworkApplyStore } = this.props;
    coworkApplyStore.setShowSearchAd(false);
  };

  onRemarkClick = (e) => {
    if (e.target.nodeName === 'IMG') {
      let img = e.target;
      img.setAttribute('data-imgsrc', img.src);
      img.setAttribute('class', 'formImgPlay');
      viewer(e);
    }
  };

  // 自定义过滤渲染
  getNewColumns = (columns) => {
    const { coworkApplyStore } = this.props;
    const { selectedKey } = toJS(coworkApplyStore);
    let newColumns = '';
    if (selectedKey == 'apply') {
      // 申请加入 页面
      newColumns = columns.map((column) => {
        let newColumn = column;
        newColumn.render = (text, record) => {
          // 前端元素转义
          if (newColumn.dataIndex == 'opt') {
            return (
              <div
                className="wea-url-apply-join"
                dangerouslySetInnerHTML={{
                  __html: getLabel(83214, '申请加入'),
                }}
                style={{ cursor: 'pointer' }}
                onClick={() => {
                  this.executeButtonMethod('batchApply', record.id);
                }}
              />
            );
          }
          let valueSpan =
            record[`${newColumn.dataIndex}span`] !== undefined
              ? record[`${newColumn.dataIndex}span`]
              : record[newColumn.dataIndex];
          return (
            <div
              className="wea-url"
              style={{ paddingRight: 10 }}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
              onClick={this.onRemarkClick}
            />
          );
        };
        return newColumn;
      });
    } else if (selectedKey == 'approval') {
      // 申请审批
    } else if (selectedKey == 'applyLog') {
      // 申请历史
      newColumns = columns.map((column) => {
        let newColumn = column;
        newColumn.render = (text, record) => {
          // 前端元素转义
          let valueSpan =
            record[`${newColumn.dataIndex}span`] !== undefined
              ? record[`${newColumn.dataIndex}span`]
              : record[newColumn.dataIndex];
          let url = '';
          if (newColumn.dataIndex == 'name') {
            url = CoworkUtil.getViewCoworkUrl(record.coworkId);
          }
          return url == '' ? (
            <div
              className="wea-url"
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          ) : (
            <div
              className="wea-url-name"
              style={{ cursor: 'pointer' }}
              onClick={() => {
                window.open(url);
              }}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          );
        };
        return newColumn;
      });
    } else if (selectedKey === 'applyquited') {
      // 已退出协作
      newColumns = columns.map((column) => {
        let newColumn = column;
        newColumn.render = (text, record) => {
          // 前端元素转义
          let valueSpan =
            record[`${newColumn.dataIndex}span`] !== undefined
              ? record[`${newColumn.dataIndex}span`]
              : record[newColumn.dataIndex];
          return newColumn.dataIndex == 'isapply' &&
            record.isapply === '1' &&
            (record.statusspan === '' || record.statusspan === '0') ? (
            <div
              className="wea-url-apply-join"
              onClick={() => {
                this.applyReJoinCowork(record);
              }}
              style={{ cursor: 'pointer' }}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          ) : (
            <div
              dangerouslySetInnerHTML={{ __html: valueSpan }}
              onClick={this.onRemarkClick}
            />
          );
        };
        return newColumn;
      });
    }
    return newColumns;
  };

  applyReJoinCowork = (data) => {
    const { coworkApplyStore } = this.props;
    let reloadTable = this.executeSearch;
    confirm({
      content: getLabel('513245', '确定申请加入吗？'),
      okText: getLabel(83446, '确定'),
      onOk() {
        coworkApplyStore.coworkApplayInfo(
          {
            coworkIds: data.coworkid,
          },
          reloadTable,
        );
      },
    });
  };

  // 表格单元格转义
  onOperatesClick = (record, index, operate, flag) => {
    const { coworkApplyStore } = this.props;
    const { selectedKey } = toJS(coworkApplyStore);

    let applyIds = record.id;
    if (selectedKey == 'approval') {
      if (flag == 0) {
        // 批准
        this.executeButtonMethod('batchApproval', applyIds);
      } else if (flag == 1) {
        // 拒绝
        this.executeButtonMethod('batchARefuse', applyIds);
      }
    }
  };
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@o880g2`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(Apply);
